package com.keeson.android_cli.base.retrofit;

import android.net.ParseException;

import com.google.gson.JsonParseException;
import com.keeson.android_cli.App;
import com.keeson.android_cli.R;
import com.keeson.android_cli.base.BaseEvent;
import com.keeson.android_cli.base.BaseRespose;
import com.keeson.android_cli.commom.Constants;
import com.keeson.android_cli.commom.EventCode;
import com.keeson.android_cli.exception.NetConnException;
import com.keeson.android_cli.util.EventBusUtils;
import com.keeson.android_cli.util.ResUtils;
import com.keeson.android_cli.util.ToastUtils;

import org.json.JSONException;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * 观察者-拦截
 *
 * @param <T> Created by gh on 2018/7/27.
 */
public abstract class BaseObserver<T> implements Observer<T> {  //BaseRespose<T>

    @Override
    public void onSubscribe(Disposable d) {

    }

    @Override
    public void onNext(T value) {

           BaseRespose<T> data = (BaseRespose<T>) value;
            if(!data.isRelogin()){
                //Log.e("onSuccess-----", JsonHelp.toJson(data)+"");
                onSuccess(value);
            }else {
                EventBusUtils.sendEvent(new BaseEvent(EventCode.EVENT_TOKEN_EXPIRE,401));
                onError(data.getMsg(), data.getCode());
            }

    }

    @Override
    public void onError(Throwable e) {

        e.printStackTrace();

        if (e instanceof SocketTimeoutException) {
            //请求超时
            onError(ResUtils.getText(R.string.str_conn_timeout), Constants.HTTP_CONN_TIMEOUTCODE);
        } else if (e instanceof NetConnException) {
            //网络未连接/网络不可用
            onError(e.getMessage(), Constants.HTTP_NET_ERRORCODE);
        } else if (e instanceof UnknownHostException || e instanceof ConnectException) {
            //连接异常
            onError(ResUtils.getText(R.string.str_conn_error), Constants.HTTP_CONN_ERRORCODE);
        } else if (e instanceof JsonParseException || e instanceof JSONException || e instanceof
                ParseException) {
            //数据解析异常
            onError(ResUtils.getText(R.string.str_data_parse_error), Constants.HTTP_DATAPARSE_ERRORCODE);
        } else {
            //其他均视为连接异常
            onError(ResUtils.getText(R.string.str_conn_error), Constants.HTTP_CONN_ERRORCODE);
        }

    }

    @Override
    public void onComplete() {

    }

    protected abstract void onSuccess(T t);

    protected void onError(String errorTip, int errorCode) {

        ToastUtils.showShort(App.getApp(), errorTip);

    }
}


